<template>
  <DFModal
    @register="modalRegister"
    ref="basicModalRef"
    :dialogTypeTitle="t(`dept.table.modalName`)"
    class="basicModal"
    @on-ok="okModal"
  >
    <template #default>
      <DFForm
        @register="modalFormRegister"
        :getLabelFrom="'table'"
        :labelPlacement="'top'"
        class="basicForm"
      >
        <template #parentId>
          <n-tree-select
            v-if="!isADmin"
            filterable
            :options="deptOptionCopy"
            :default-value="defaultIndex"
            label-field="deptName"
            key-field="deptId"
            :default-expand-all="true"
            @update:value="treeSelect"
          />
        </template>
      </DFForm>
    </template>
  </DFModal>
</template>

<script lang="ts" setup name="DeptModal">
  // import { Ref } from 'vue';
  import {
    // useMessage,
    FormItemRule,
  } from 'naive-ui';
  import { DFModal, useModal } from '@/components/DFModal';
  import { DFForm, FormSchema, useForm } from '@/components/DFForm/index';
  import { checkEmailFn } from '@/utils/formCheck';
  // import { addDept, updateDept } from '@/api/system/dept';
  import { cloneDeep } from 'lodash-es';
  import { t } from '@/i18n';

  // type Props = {
  //   modalType?: string;
  // };

  // const props = withDefaults(defineProps<Props>(), {
  //   modalType: () => '',
  // });
  const defaultIndex = ref<number>(-1);
  const emit = defineEmits(['reloadFn', 'register']);
  // const message = useMessage();

  const deptOption = inject<any>('deptOption');
  const deptOptionCopy = inject<any>('deptOptionCopy');
  // let editData = {};
  const treeSelect = (_: number, model: any) => {
    const data = { ...cloneDeep(getModalFormValFn()) };
    setFieldsValue({ ...data, parentId: model.deptId });
  };
  const isADmin = ref(false);
  const modalFormSchemas = computed((): FormSchema[] => {
    return [
      {
        field: 'parentId',
        component: 'NInput',
        label: 'parentId',
        defaultValue: '',
        slot: 'parentId',
        hidden: isADmin,
        componentProps: {
          maxlength: 30,
          clearable: true,
        },
        rules: [{ type: 'number', required: true, message: '', trigger: ['blur'] }],
      },
      {
        field: 'deptName',
        component: 'NInput',
        label: 'deptName',
        defaultValue: '',
        componentProps: {
          maxlength: 60,
          clearable: true,
        },
        rules: [{ required: true, message: '', trigger: ['blur'] }],
      },
      {
        field: 'orderNum',
        component: 'NInput',
        label: 'orderNum',
        defaultValue: '0',
        componentProps: {
          type: 'number',
          maxlength: 30,
          clearable: true,
          onBlur: () => {
            const data = { ...cloneDeep(getModalFormValFn()) };
            const { orderNum } = data;
            if (Number(orderNum) < 0) setFieldsValue({ ...data, orderNum: '0' });
            if (orderNum.length > 5) setFieldsValue({ ...data, orderNum: orderNum.slice(0, 5) });
          },
        },
        rules: [{ required: true, message: '', trigger: ['blur'] }],
      },
      {
        field: 'leader',
        component: 'NInput',
        label: 'leader',
        defaultValue: '',
        componentProps: {
          maxlength: 20,
          clearable: true,
        },
        rules: [{ required: true, message: '', trigger: ['blur'] }],
      },
      {
        field: 'phone',
        component: 'NInput',
        label: 'phone',
        defaultValue: '',
        componentProps: {
          maxlength: 20,
          clearable: true,
        },
        rules: [
          {
            required: false,
            message: t('common.formTipMsg.input'),
            trigger: ['blur'],
          },
          {
            pattern: /^([0-9]|-|\+)+$/g,
            message: t('common.formTipMsg.phoneNo'),
            trigger: ['blur', 'input'],
          },
        ],
      },
      {
        field: 'email',
        component: 'NInput',
        label: 'email',
        defaultValue: '',
        componentProps: {
          maxlength: 50,
          clearable: true,
        },
        rules: [
          {
            required: false,
            validator(_rule: FormItemRule, value: string) {
              return checkEmailFn(value, false);
            },
            trigger: ['blur'],
          },
        ],
      },
    ];
  });

  const [modalRegister, { openModal, closeModal, setSubLoading }] = useModal({});

  const [modalFormRegister, { validate, getFieldsValue: getModalFormValFn, setFieldsValue }] =
    useForm({
      gridProps: { cols: 1 },
      collapsedRows: 3,
      labelWidth: 120,
      layout: 'horizontal',
      showActionButtonGroup: false,
      schemas: modalFormSchemas,
    });

  const okModal = async (): Promise<void> => {
    try {
      const isSubmit = await validate();
      if (isSubmit) return;
      const data = { ...cloneDeep(getModalFormValFn()) };
      data['permissionCodeList'] = [];
      // const { message: msg = '' } =
      //   props.modalType === 'add'
      //     ? await addDept(data)
      //     : await updateDept({ ...editData, ...data });
      emit('reloadFn');
      closeModal();
      // message.success(msg || t('common.tipMsg.saveSuccess'));
    } catch (e) {
      console.log(e);
      setSubLoading(false);
    }
  };

  const findIndex = (list: any, id: number) => {
    for (const item of list) {
      if (item.deptId === id) return item;
      if (item.children && item.children.length) {
        const _item = findIndex(item.children, id);
        if (_item) return _item;
      }
    }
  };
  const openModalFn = async (
    type: string,
    data: Record<string, any> | undefined,
    title?: string
  ) => {
    isADmin.value = false;
    defaultIndex.value = -1;
    // editData = {};
    openModal(type, title);
    if (data) {
      // editData = cloneDeep(data);
      if (type === 'edit') {
        isADmin.value = data.parentId === 0 ? true : false;
        defaultIndex.value =
          data.parentId === 0
            ? data.deptId
            : findIndex(deptOption.value, data.deptId)?.parentId ?? data.deptId;
        console.log(
          'defaultIndex.value',
          deptOption.value,
          data.deptId,
          findIndex(deptOption.value, data.deptId)?.parentId
        );
      } else if (type === 'add' && data) {
        isADmin.value = false;
        defaultIndex.value = data.deptId;
        data = { parentId: data.deptId };
        // editData = cloneDeep(data);
      }

      nextTick(() => {
        setFieldsValue(data);
      });
    }
  };

  defineExpose({ openModalFn });
</script>
